let network = require("./network/network");
let api = require("./network/config.js").api;

function getUserProfile() {
  let _this = this
  wx.showModal({
    title: '提示',
    content: '请点击确认以快速登录',
    complete: (res) => {
      if (res.cancel) {

      }

      if (res.confirm) {
        wx.getUserProfile({
          desc: '用于展示用户昵称、头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            login();
            getApp().globalData.userSession = res.userInfo;
            getApp().globalData.isLogin = true;

            wx.setStorageSync('userSession', res.userInfo)

          },
          fail: (e) => {
            console.log(e)
          }
        })
      }
    }
  })

}

function login() {
  let _this = this
  wx.login({
    success(res) {
      if (res.code) {
        //发起网络请求
        network.fetch({
            url: api.user_login,
            data: {
              code: res.code
            },
            inBody: false,
            method: 'GET',
          })
          .then(res => {
            wx.setStorageSync('userInfo', res.data)
            getApp().globalData.userInfo = res.data;

            updateUserInfo();
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    }
  })
}

function updateUserInfo() {
  let userSession = getApp().globalData.userSession
  let uid = getApp().globalData.userInfo.uid
  let data = {
    nickName: userSession.nickName,
    uid: uid,
    avatarUrl: userSession.avatarUrl,
  }
  network.fetch({
      url: api.user_update,
      data: data,
      inBody: true,
      method: 'POST',
    })
    .then(res => {
      console.log(res)
    })
}
module.exports = {
  getUserProfile
}